﻿#region Licence
// <copyright file="Core/AccueilViewModel.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Core.Class;
using Database.POCO;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using Helpers.Mef;
using Helpers.Messages;
using Interfaces.Contracts;
using Interfaces.Enums;

#endregion

namespace Core.ViewModel
{
    /// <summary>
    /// Permet d'afficher les informations d'accueil provenant des modules
    /// </summary>
    public class AccueilViewModel : ViewModelBaseCore, IPartImportsSatisfiedNotification
    {
        #region properties

        [ImportMany(typeof(IAccueilContract))]
        public IEnumerable<Lazy<IAccueilContract, IAccueilMetadata>> ModulesAccueilImported { get; set; }

        private List<AccueilModuleUi> _modulesAccueil;
        public List<AccueilModuleUi> ModulesAccueil
        {
            get { return _modulesAccueil; }
            set
            {
                _modulesAccueil = value;
                RaisePropertyChanged(() => ModulesAccueil);
            }
        }

        #endregion

        public AccueilViewModel()
        {
            CompositionInitializer.AddPartAndComposeContainer(this);
        }

        #region public
        
        /// <summary>
        /// Permet d'importer et d'afficher les modules
        /// </summary>
        public void OnImportsSatisfied()
        {
            if (ModulesAccueilImported != null && ModulesAccueilImported.Any() && ModulesAccueil == null)
            {
                var modulesToCreate = new List<AccueilModuleUi>();
                foreach (var module in ModulesAccueilImported)
                {
                    //Création des droits pour les modules
                    Lazy<IAccueilContract, IAccueilMetadata> module1 = module;
                    if (!DatabaseService.Service.Where<SysDroits>(d => d.IdentifiantDroit == module1.Metadata.Identifier).Any())
                    {
                        DatabaseService.Service.Save<SysDroits>(new SysDroits { IdentifiantDroit = module.Metadata.Identifier, LibelleDroit = LocalizedService.LocalizedFromKey(string.Format("{0}Right", module.Metadata.Name)), Module = (int)module.Metadata.Module, IsSimpleFonction = true });
                    }

                    //Vérification des droits d'accés
                    if (AccessControlService.IsAuthorizedFunction(module.Metadata.Identifier))
                    {
                        Lazy<IAccueilContract, IAccueilMetadata> moduleToLoad = module;
                        var moduleAccueil = new AccueilModuleUi()
                        {
                            Libelle = LocalizedService.LocalizedFromKey(moduleToLoad.Metadata.Name),
                            UserControl = (ViewModelBase)moduleToLoad.Value,
                            RefreshCommand = new RelayCommand<IAccueilContract>(p => p.Refresh(this))
                        };
                        modulesToCreate.Add(moduleAccueil);
                    }
                }
                ModulesAccueil = modulesToCreate;

                //On lance un refresh automatique
                RefreshDatas();
            }
        }

        /// <summary>
        /// Permet de lancer le refresh de tous les modules
        /// </summary>
        public void RefreshDatas()
        {
            Messenger.Default.Send<CurrentModuleMessage>(new CurrentModuleMessage() { CurrentModule = TypeModulesEnum.None });
            if (ModulesAccueil != null)
            {
                foreach (var moduleUi in ModulesAccueil)
                {
                    ((IAccueilContract) moduleUi.UserControl).Refresh(this);
                }
            }
        }
        #endregion
    }
}
